<?php

class ClassAdmin extends ClassOption {

    public function table_crud($mConfig, $oRes, $class_qiniu, $db_cmf, $method, $pageParams, $queryParams, $sortParams, $oper_id, $formValue, $uploadFile) {
        //$mConfig['id'] = $mConfig['column']['id']['prop'];
        $sTableName = $mConfig['name'];
        $sTableAlias = empty($mConfig['alias']) ? 't1' : $mConfig['alias'];
        unset($mConfig['name']);
        $oSql = $db_cmf->sql()->table('{tablepre}' . $sTableName . ' ' . $sTableAlias);
        if (isset($mConfig['join'])) {
            $oSql->join($mConfig['join']);
        }
        unset($mConfig['join']);
        $mField = array();
        foreach ($mConfig['column'] as $col) {
            if (empty($col['prop'])) {
                continue;
            }
            $ta = empty($col['table']) ? $sTableAlias : $col['table'];
            $mField[$ta . '.' . $col['prop']] = 1;
        }
        $allField = array_keys($mField);
        $oSql->field(implode(',', $allField));
        $fCheckQuery = function($paramName)use($queryParams) {
            if (!isset($queryParams[$paramName])) {
                //如果这个参数不存在就不参与WHERE条件
                return false;
            }
            $d = $queryParams[$paramName];
            if (is_string($d)) {
                //如果是字符串
                if (strlen($d) === 0) {
                    //空的字符串不参与WHERE条件
                    return false;
                }
            }
            if (is_array($d)) {
                //如果是数组
                if (count($d) === 0) {
                    //空数组不参与WHERE条件
                    return false;
                }
                foreach ($d as $item) {
                    if ($item == null) {
                        //数组内只要有一个null就不参与WHERE条件
                        return false;
                    }
                }
            }
            return true;
        };
        if (empty($mConfig['page'])) {
            $mConfig['page'] = array();
        }
        if (empty($mConfig['page']['limit'])) {
            $mConfig['page']['limit'] = 100;
        }
        if (empty($mConfig['page']['size_list'])) {
            $mConfig['page']['size_list'] = array();
            $mConfig['page']['size_list'][] = 100;
            $mConfig['page']['size_list'][] = 200;
            $mConfig['page']['size_list'][] = 500;
            $mConfig['page']['size_list'][] = 1000;
        }
        switch ($method) {
            case('list'):
                foreach ($mConfig['column'] as &$columnInfo1) {
                    if (isset($columnInfo1['select'])) {
                        if (empty($columnInfo1['select']['db'])) {
                            $columnInfo1['select']['db'] = $db_cmf;
                        }
                        $columnInfo1['option'] = $this->GetSelectData($columnInfo1['select']);
                        unset($columnInfo1['select']);
                    }
                }
                $oRes->assign('data', $mConfig);
                $aWhere = array();
                $sWhereSql = '1';
                if (isset($mConfig['filter'])) {
                    if (isset($mConfig['filter']['sql'])) {
                        $sWhereSql = $mConfig['filter']['sql'];
                    }
                }
                $mField = array();
                foreach ($mConfig['column'] as $columnInfo) {
                    if (empty($columnInfo['prop'])) {
                        continue;
                    }
                    $columnName = $columnInfo['prop'];
                    $columnTable = empty($columnInfo['table']) ? $sTableAlias : $columnInfo['table'];
                    if (isset($columnInfo['width'])) {
                        $mField[$columnTable . '.' . $columnName] = 1;
                    }
                    if (empty($columnInfo['where'])) {
                        continue;
                    }
                    if ($fCheckQuery($columnName)) {
                        $sWhereType = $columnInfo['where'];
                        switch ($sWhereType) {
                            case('eq'):
                                $aWhere[$columnName] = trim($queryParams[$columnName]);
                                $sWhereSql .= ' AND ' . $columnTable . '.`' . $columnName . '`=:' . $columnName;
                                break;
                            case('like'):
                                $aWhere[$columnName] = '%' . trim($queryParams[$columnName]) . '%';
                                $sWhereSql .= ' AND ' . $columnTable . '.`' . $columnName . '` LIKE :' . $columnName;
                                break;
                            case('between'):
                                if (!is_array($queryParams[$columnName]) || count($queryParams[$columnName]) < 2) {
                                    continue 2;
                                }
                                $aWhere['begin'] = $queryParams[$columnName][0];
                                $aWhere['end'] = $queryParams[$columnName][1];
                                // switch ($columnInfo['search_type']) {
                                if (0) {
                                    $sWhereSql .= ' AND ' . $columnTable . '.`' . $columnName . '` BETWEEN :begin AND DATE_ADD(:end,INTERVAL 1 DAY)';
                                } else {
                                    $sWhereSql .= ' AND ' . $columnTable . '.`' . $columnName . '` BETWEEN :begin AND :end';
                                }
                        }
                    }
                }
                $oSql->field(implode(',', array_keys($mField)));
                $oSql->where($aWhere, $sWhereSql);
                if (TRUE) {
                    $pageNum = isset($pageParams['pageNum']) ? intval($pageParams['pageNum']) : 1;
                    if ($pageNum < 1) {
                        $pageNum = 1;
                    }
                    $pageSize = isset($pageParams['pageSize']) ? intval($pageParams['pageSize']) : 10;
                    $oSql->limit($pageSize, $pageSize * ($pageNum - 1));
                }
                $fGetFullField = function ($_shortField) use ($allField) {
                    foreach ($allField as $fullField) {
                        $aFullField = explode('.', $fullField);
                        $shortField = $aFullField[1];
                        if ($shortField === $_shortField) {
                            return $fullField;
                        }
                    }
                    return $mConfig['sort']['prop'];
                };
                $prop = empty($sortParams['prop']) ? $mConfig['sort']['prop'] : $fGetFullField($sortParams['prop']);
                $order = empty($sortParams['order']) ? $mConfig['sort']['order'] : $sortParams['order'];
                switch ($order) {
                    case ('ascending'):
                        $oSql->order($prop);
                        break;
                    case ('descending'):
                        $oSql->desc($prop);
                        break;
                }
                $aRows = $oSql->select();
                foreach ($aRows as &$mRow) {
                    foreach ($mConfig['column'] as $col) {
                        if (empty($col['prop'])) {
                            continue;
                        }
                        if (empty($mRow[$col['prop']])) {
                            continue;
                        }
                        if (isset($col['form'])) {
                            switch ($col['form']) {
                                case ('upload'):
                                    $mRow[$col['prop']] = $this->ReplaceStorageUrl($mRow[$col['prop']]);
                            }
                        }
                        if (isset($col['set'])) {
                            $aSet = $col['set'];
                            foreach ($aSet as $set) {
                                if (strtolower($set) === 'upper') {
                                    $mRow[$col['prop']] = strtoupper($mRow[$col['prop']]);
                                }
                            }
                        }
                    }
                }
                $oRes->data('rows', $aRows);
                $oRes->data('total', $oSql->count());
                break;
            case('get'):
                $aWhere = array();
                $aWhere[$sTableAlias . '.' . $mConfig['id'] . ''] = $oper_id;
                $mRow = $oSql->where($aWhere)->find();
                foreach ($mConfig['column'] as $col) {
                    if (empty($col['form'])) {
                        continue;
                    }
                    if (empty($col['prop'])) {
                        continue;
                    }
                    if (!isset($mRow[$col['prop']])) {
                        continue;
                    }
                    switch ($col['form']) {
                        case('input'):
                            if ($col['type'] === 'radio') {
                                //$mRow[$col['prop']] = intval($mRow[$col['prop']]);
                            }
                            break;
                        case('upload'):
                            $mRow[$col['prop']] = $this->ReplaceStorageUrl($mRow[$col['prop']]);
                            break;
                        case('color'):
                            $mRow[$col['prop']] = '#' . strtoupper($mRow[$col['prop']]);
                            break;
                    }
                }
                $oRes->data('formValue', $mRow);
                break;
            case('create'):
            case('update'):
                $mData = array();
                foreach ($mConfig['column'] as $col) {
                    if (empty($col['form'])) {
                        continue;
                    }
                    if (empty($col['prop'])) {
                        continue;
                    }
                    if (!isset($formValue[$col['prop']])) {
                        continue;
                    }
                    $mData[$col['prop']] = $formValue[$col['prop']];
                    switch ($col['form']) {
                        case('color'):
                            $mData[$col['prop']] = ltrim($mData[$col['prop']], '#');
                            break;
                    }
                }
                $oSql->table($sTableName);
                if ($method === 'create') {
                    // 添加
                    $oSql->add($mData);
                    $oRes->assign('msg', $mConfig['title'] . '添加成功');
                } else if ($method === 'update') {
                    // 修改
                    $aWhere = array();
                    $aWhere[$mConfig['id']] = $formValue[$mConfig['id']];
                    $oSql->where($aWhere)->save($mData);
                    $oRes->assign('msg', $mConfig['title'] . '修改成功');
                }
                $db_cmf->commit();
                if ($sTableName === 'experlevel') {
                    $this->cache_del($oRes, 'table_experlevel_table');
                }
                break;
            case('delete'):
                $oSql->table($sTableName);
                $aWhere = array();
                $aWhere[$mConfig['id']] = $oper_id;
                $oSql->where($aWhere);
                $oSql->delete();
                $db_cmf->commit();
                if ($sTableName === 'experlevel') {
                    $this->cache_del($oRes, 'table_experlevel_table');
                }
                break;
            case('upload'):
                $action = 'cmf_admin';
                $filename = $mConfig['upload']['name'] . '/' . $uploadFile['name'];
                $oRes->data('upload_form', $class_qiniu->GetUploadForm($action, $filename, 'admin'));
                break;
        }
    }

    private function GetSelectData($mSelect) {
        $oSql = $mSelect['db']->sql();
        $oSql->table($mSelect['table']);
        $aField = array();
        $aField[] = $mSelect['field_value'] . ' id';
        $aField[] = $mSelect['field_title'] . ' title';
        $oSql->field(implode(',', $aField));
        if (isset($mSelect['where'])) {
            $oSql->where($mSelect['where']);
        }
        $aRows = $oSql->select();
        $mRet = array();
        foreach ($aRows as $mRow) {
            $mRet[$mRow['id']] = $mRow['title'];
        }
        return (object) $mRet;
    }

}
